package com.slipper.sfts.stock.service;

import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.slipper.common.transaction.ReadTransactional;
import com.slipper.common.transaction.WriteTransactional;
import com.slipper.common.util.GsonUtil;
import com.slipper.common.util.StringUtil;
import com.slipper.common.util.Tool;
import com.slipper.qmt.redis.RedisSender;
import com.slipper.sfts.api.stock.bo.StockOrderMessageBO;
import com.slipper.sfts.stock.dao.StockOrderMessageDao;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

@Service
@ReadTransactional
public class StockOrderMessageService {
    @Resource
    private RedisSender sender;
    @Resource
    private StockOrderMessageDao stockOrderMessageDao;
    
    public StockOrderMessageBO queryBy(String id) {
        return stockOrderMessageDao.queryBy(id);
    }
    
    public List<StockOrderMessageBO> queryList(StockOrderMessageBO bo) {
        return stockOrderMessageDao.queryList(bo);
    }
    
    public PageInfo<StockOrderMessageBO> queryPage(StockOrderMessageBO bo) {
        PageHelper.startPage(bo.getPageNumber(), bo.getPageSize());
        return new PageInfo<>(stockOrderMessageDao.queryList(bo));
    }
    
    @WriteTransactional
    public int save(StockOrderMessageBO bo) {
        if (bo.getId() != null && !"".equals(bo.getId())) {
            return stockOrderMessageDao.update(bo);
        } else {
            bo.setId(Tool.getUUID());
            return stockOrderMessageDao.insert(bo);
        }
    }

    @WriteTransactional
    public int save(String memberId, String accountId, String message) {
        if (StringUtil.isBlank(message)) {
            return 0;
        }

        StockOrderMessageBO bo = new StockOrderMessageBO();
        bo.setId(Tool.getUUID());
        bo.setMemberId(memberId);
        bo.setAccountId(accountId);
        if (message.length() > 1000) {
            bo.setMessage(message.substring(0, 1000));
        } else {
            bo.setMessage(message);
        }

        if (StringUtil.isNotBlank(memberId)) {
            String topic = "on_member_message_" + memberId;
            Map<String, Object> data = new HashMap<>();
            data.put("message", message);
            sender.sendMsg(topic, GsonUtil.toJson(data));
        }
        return stockOrderMessageDao.insert(bo);
    }
    
    @WriteTransactional
    public int delete(StockOrderMessageBO bo) {
        return stockOrderMessageDao.delete(bo);
    }
}
